﻿using System;
using System.Collections.Generic;
using System.Text;

namespace T.FAS.Runtime.Metadata.Dao
{
    using System.Data;
    using System.Linq;
    using T.FAS.Runtime.Metadata.Entity;   
    using T.ServiceComponent.DAC.Service;
    using T.ServiceComponent.DataAccessEx.Core;

    public class MetaDataRelationDao : DaoService<MetaDataRelation>
    {
        public MetaDataRelationDao(string db = "TFAS") : base()
        {
            this.DBName = db;
        }

        public override string IDColumnName
        {
            get
            {
                return "ID";
            }
        }

        public override string TableName
        {
            get
            {
                return "ADP_MetadataRelation";
            }
        }

        public void Save(IList<MetaDataRelation> metadataRelations)
        {
            if (metadataRelations == null || metadataRelations.Count == 0)
            {
                return;
            }

            base.Add(metadataRelations.ToList());
        }

        /// <summary>
        /// 查询依赖的元数据
        /// </summary>
        /// <param name="metadataID">元数据ID</param>
        /// <param name="metaDataType">元数据类型</param>
        /// <param name="metaDataVersion">元数据版本</param>
        /// <returns>依赖的元数据</returns>
        public List<MetaDataRelation> GetMetadataRelations(string metadataID, string metaDataType, string metaDataVersion)
        {
            if (string.IsNullOrWhiteSpace(metadataID))
                throw new ArgumentNullException("MetadataRelationDao.GetMetadataRelations.metadataID");
            if (string.IsNullOrWhiteSpace(metaDataType))
                throw new ArgumentNullException("MetadataRelationDao.GetMetadataRelations.metaDataType");
            if (string.IsNullOrWhiteSpace(metaDataVersion))
                throw new ArgumentNullException("MetadataRelationDao.GetMetadataRelations.metaDataVersion");

            var result = new List<MetaDataRelation>();
            var sql = string.Format("SELECT * FROM {0} WHERE MetaDataID=:MetaDataID and MetaDataType=:MetaDataType and MetaDataVersion=:MetaDataVersion");

            var parameters = new List<IDbDataParameter>(3);
            parameters.Add(DB.MakeInParam(":MetaDataID", TDbDataType.VarChar, metadataID));
            parameters.Add(DB.MakeInParam(":MetaDataType", TDbDataType.VarChar, metaDataType));
            parameters.Add(DB.MakeInParam(":MetaDataVersion", TDbDataType.VarChar, metaDataVersion));

            var ds = DB.ExecuteDataSet(sql, parameters);
            if (ds != null)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    var row = ds.Tables[0].Rows[i];

                    result.Add(ConvertToObject(this.GetColumns(), row));
                }
            }

            return result;
        }
    }
}
